<template>
  <el-dialog title="选择成员" :visible.sync="visible" width="1200px" top="5vh" append-to-body>
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :span="6">
        <el-scrollbar style="height: 480px">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-scrollbar>
      </el-col>

      <!-- 用户列表 -->
      <el-col :span="18">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item label="账号名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :row-style="{ height: '35px' }"
          :cell-style="{ padding: '0px' }"
          @row-click="clickRow"
          ref="table"
          :data="userList"
          @selection-change="handleSelectionChange"
          height="395px"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" type="index" :index="indexMethod" width="60" />
          <el-table-column label="账号名称" prop="userName" :show-overflow-tooltip="true" align="center" width="200" />
          <el-table-column label="用户姓名" prop="nickName" :show-overflow-tooltip="true" align="center" width="150" />
          <el-table-column label="职位" prop="position" :show-overflow-tooltip="true" align="center" width="80" />
          <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" align="center" width="120" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSelectUser">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listUser } from "@/api/system/user";
import { deptTreeSelect } from "@/api/system/user";

export default {
  props: {
    // 已选成员列表
    selectedMembers: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 遮罩层
      visible: false,
      // 部门树选项
      deptOptions: undefined,
      // 树形配置
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 选中数组
      selectedUsers: [],
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        deptId: null,
        userName: undefined,
        phonenumber: undefined
      },
      // 已选成员ID集合，用于回显和过滤
      selectedMemberIds: new Set()
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        // 获取部门树后再获取用户列表
        this.getList()
      })
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    show() {
      this.visible = true
      // 先获取部门树，不要直接调用 getList
      this.getDeptTree()
    },
    cancel() {
      this.visible = false
      this.resetForm("queryForm")
    },
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    handleSelectUser() {
      if (this.selectedUsers.length === 0) {
        this.$modal.msgError("请选择要添加的成员")
        return
      }

      const members = this.selectedUsers.map(user => ({
        memberName: user.nickName,
        userId: user.userId,
        contactInfo: user.phonenumber,
        position: user.position || '',
        deptName: user.dept?.deptName || ''
      }))

      this.$emit('select', members)
      this.visible = false
    },
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
    },
    getList() {
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        // 获取数据后初始化选中状态
        this.initSelection()
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.deptId = null
      this.handleQuery()
    },
    /** 初始化选中状态 */
    initSelection() {
      // 清空之前的选择
      this.$refs.table.clearSelection()
      // 构建已选成员ID集合
      this.selectedMemberIds = new Set(this.selectedMembers.map(m => m.userId))
      // 设置表格选中状态
      this.$nextTick(() => {
        this.userList.forEach(user => {
          if (this.selectedMemberIds.has(user.userId)) {
            this.$refs.table.toggleRowSelection(user, true)
          }
        })
      })
    }
  }
}
</script>

<style scoped>
.el-scrollbar {
  border-right: 1px solid #dfe6ec;
}
</style>
